//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, {useState } from "react";
import { observer } from 'mobx-react';
import type { AuthSecretInfo } from "@/api/dragonfly/config";
import { add_auth_secret, update_auth_secret } from "@/api/dragonfly/config";
import { Form, Input, message, Modal } from "antd";
import { useDragonFlyStores } from "../store";
import { get_session } from "@/api/user";
import { request } from "@/utils/request";
import { gen_access_token } from "@/api/project_server";

const NumAndString = /^[0-9a-zA-Z]+$/;

export interface EditSecretModalProps {
    secret?: AuthSecretInfo;
    onCancel: () => void;
    onOk: () => void;
}

const EditSecretModal = (props: EditSecretModalProps) => {
    const appStore = useDragonFlyStores();

    const [username, setUsername] = useState(props.secret?.username ?? "");
    const [password, setpassword] = useState(props.secret?.password ?? "");
    const [hasChange, setHasChange] = useState(false);

    const valid = () => {
        if (hasChange && password.length >= 8 && NumAndString.test(username)) {
            return true;
        }
        return false;
    };

    const addSecret = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));
        await request(add_auth_secret(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            auth_secret: {
                username,
                password,
            },
        }));
        message.info("增加成功");
        props.onOk();
    };

    const updateSecret = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));
        await request(update_auth_secret(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            auth_secret: {
                username,
                password,
            },
        }));
        message.info("修改成功");
        props.onOk();
    };

    return (
        <Modal open title={props.secret == undefined ? "增加密钥" : "修改密钥"} mask={false}
            okText={props.secret == undefined ? "增加" : "修改"} okButtonProps={{ disabled: !valid() }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (props.secret == undefined) {
                    addSecret();
                } else {
                    updateSecret();
                }
            }}>
            <Form labelCol={{ span: 3 }}>
                <Form.Item label="用户名" help={
                    <>
                        {NumAndString.test(username) == false && (
                            <span style={{ color: "red" }}>用户名只能包含字母和数字</span>
                        )}
                    </>
                }>
                    <Input value={username} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setUsername(e.target.value.trim());
                        setHasChange(true);
                    }} disabled={props.secret != undefined} status={NumAndString.test(username) ? undefined : "error"}
                        placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item label="密钥" help={
                    <>
                        {password.length < 8 && (
                            <span style={{ color: "red" }}>密钥需要8位以上长度</span>
                        )}
                    </>
                }>
                    <Input.Password value={password} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setpassword(e.target.value.trim());
                        setHasChange(true);
                    }} status={password.length < 8 ? "error" : undefined} placeholder="请输入密码" />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default observer(EditSecretModal);